package com.dg.river.module.base.proxy;


import com.dg.river.core.inject.Presenter;
import com.dg.river.module.base.presenter.BasePresenterImpl;
import com.dg.river.module.base.view.IBaseView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者：Hututu
 * @时间：2022/6/13 15:27
 * @描述：内容描述
 * @修改：修改内容
 * @Version:1.0
 */
public class ProxyImpl implements IProxy {

    private final IBaseView view;

    private List<BasePresenterImpl> mInjectPresenters;

    public ProxyImpl(IBaseView view) {
        this.view = view;
        mInjectPresenters = new ArrayList<>();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void bindPresenter() {
        Field[] declaredFields = view.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            // 获取变量上面的注解类型
            Presenter presenter = field.getAnnotation(Presenter.class);
            if (presenter != null) {
                Class<? extends BasePresenterImpl> type = (Class<? extends BasePresenterImpl>) field.getType();
                try {
                    BasePresenterImpl mInjectPresenter = type.newInstance();
                    mInjectPresenter.attachView(view);
                    field.setAccessible(true);
                    field.set(view, mInjectPresenter);
                    mInjectPresenters.add(mInjectPresenter);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    throw new RuntimeException("SubClass must extends Class:BasePresenter");
                }
            }
        }
    }

    @Override
    public void unBindPresenter() {
        for (BasePresenterImpl mInjectPresenter : mInjectPresenters) {
            mInjectPresenter.detachView();
        }
        mInjectPresenters.clear();
        mInjectPresenters = null;
    }
}
